package com.ruoyi.common.utils;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MultipartFileUtil {

    protected static Log logger = LogFactory.getLog(MultipartFileUtil.class);

    final static Pattern fileExt = Pattern.compile("\\.(\\w+)$");

    public static String getFileExt(String file) {
        if (file == null) {
            return "";
        }
        Matcher m = fileExt.matcher(file);
        return m.find() ? m.group(1) : "";
    }

    public static String getFileName(MultipartFile file) {
        return getFileName(file, false);
    }

    public static String getFileName(MultipartFile file, boolean removeExtension) {

        String fileName = null;

        try {

            String originalFilename = file.getOriginalFilename();
            int ind = originalFilename.lastIndexOf(".");

            byte[] bytes = file.getBytes();

            fileName = Md5Utils.md5(bytes);

            if (ind > 0 && removeExtension == false) {
                fileName = fileName + originalFilename.substring(ind);
            }

        } catch (IOException ie) {
            logger.error(ie.getMessage(), ie);
        }

        return fileName;
    }

    public static String getRandName(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        int ind = originalFilename.lastIndexOf(".");
        return UUID.randomUUID().toString().replaceAll("-", "") + originalFilename.substring(ind);
    }

    public static long getFileSize(MultipartFile file) {

        try {

            return file.getBytes().length;

        } catch (IOException ie) {
            logger.error(ie.getMessage(), ie);
        }

        return 0;
    }

}
